package com.cskaoyan.udp.edition2;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/*
        发送端
 */
public class Sender {

    public static void main(String[] args) throws IOException {

        // 创建用于接收键盘录入的字符串的缓冲字符输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 准备用于接收数据的数据报包
        byte[] bytes = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(bytes, 0, bytes.length);

        // 1. 创建用于发送数据的DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket(9999);


        String line;
        while ((line = br.readLine()) != null) {
            // 给接收方发送数据
            sendData(datagramSocket, line);
            // 接收 接收方发送的数据
            receiveResponse(receivePacket, datagramSocket);


            if ("886".equals(line)) {
                // 根据自定义协议
                break;
            }
        }
        // 关闭socket
        datagramSocket.close();


    }

    private static void receiveResponse(DatagramPacket receivePacket, DatagramSocket datagramSocket) throws IOException {
        // 阻塞方法
        datagramSocket.receive(receivePacket);
        // 4. 解析接收到的数据
        byte[] data = receivePacket.getData();
        int offset = receivePacket.getOffset();
        int length = receivePacket.getLength();

        String s = new String(data, offset, length);
        System.out.println(s);
    }

    private static void sendData(DatagramSocket datagramSocket, String line) throws IOException {
        // 将待发送的数据封装到数据报包中
        byte[] bytes = line.getBytes();

        InetAddress targetIp = InetAddress.getByName("localhost");
        int port = 9898;
        DatagramPacket sendPacket = new DatagramPacket(bytes, 0, bytes.length, targetIp, port);


        // 发送数据报包
        datagramSocket.send(sendPacket);
    }
}
